<?php

namespace Wonfu\Core\Database;

use Cake\Database\Log\LoggedQuery;
use Cake\Database\Log\LoggingStatement;
use Cake\Database\Query;
use Cake\Database\StatementInterface;
use Psr\Log\LoggerInterface;

class CakeConnectionWrapper extends \Cake\Database\Connection
{



    /**
     * Logs a Query string using the configured logger object.
     *
     * @param string $sql string to be logged
     * @return void
     */
    public function log(string $sql): void
    {
        $query = new LoggedQuery();
        $query->query = $sql;
        $this->getLogger()->info((string)$query);
    }

    /**
     * Returns a new statement object that will log the activity
     * for the passed original statement instance.
     *
     * @param StatementInterface $statement the instance to be decorated
     * @return CakeLoggingStatementWrapper
     */
    protected function getCakeLoggingStatementWrapper(StatementInterface $statement)
    {
        $log = new CakeLoggingStatementWrapper($statement, $this->_driver);
        $log->setLogger($this->getLogger());
        return $log;

    }

    /**
     * Prepares a SQL statement to be executed.
     *
     * @param Query|string $query The SQL to convert into a prepared statement.
     * @return StatementInterface
     */
    public function prepare($query): StatementInterface
    {
        return $this->getDisconnectRetry()->run(function () use ($query) {
            $statement = $this->_driver->prepare($query);

            if ($this->_logQueries) {
                $statement = $this->getCakeLoggingStatementWrapper($statement);
            }

            return $statement;
        });
    }

}